/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.table.key.changeKey.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.CommonTableRpcService;
import com.je.common.base.util.*;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.metadata.IdType;
import com.je.meta.cache.table.TableCache;
import com.je.meta.service.MetaStaticizeService;
import com.je.meta.service.table.key.ChangePrimaryKeyService;
import com.je.meta.util.enumUtil.TableTypeEnum;
import com.je.servicecomb.RpcSchemaFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.je.servicecomb.JECloud.PRODUCT_CORE_META;

@Service
public class ChangePrimaryKeyServiceImpl implements ChangePrimaryKeyService {

    @Autowired
    private MetaService metaService;

    @Autowired
    private MetaStaticizeService metaStaticizeService;

    @Autowired
    private TableCache tableCache;

    @Autowired
    private CommonService commonService;


    @Override
    public String checkLocal(DynaBean table) {
        String result="";
        if (StringUtil.isEmpty(result) && !table.getStr("RESOURCETABLE_TYPE").equals(TableTypeEnum.VIEW.getValue())) {
            result = checkIsExistsData(table.getStr("RESOURCETABLE_TABLECODE"), table.getStr("SY_PRODUCT_CODE"));
        }
        return result;
    }

    @Override
    public String checkMeta(String newPrimaryKey,DynaBean table) {
        String result="";
        //新的主键编码不能和当前主键编码一样
        if(newPrimaryKey.equals(getPkCode(table.getStr("RESOURCETABLE_TABLECODE")))){
            result = MessageUtils.getMessage("table.pkCode.same");
        }
        //校验编码的格式
        if(StringUtil.isEmpty(result)){
            boolean matches = newPrimaryKey.matches("^[a-zA-Z]{1}[a-zA-Z_0-9]{0,40}$");
            if(!matches){
                result = MessageUtils.getMessage("table.column.code.format1.error");
            }
        }
        //主键策略为自增时不能更换主键
        if(IdType.AUTO.getValue().equals(table.getStr("RESOURCETABLE_KEY_GENERATOR_TYPE"))){
            result = MessageUtils.getMessage("table.strategy.isAutoincrement.connot.changePk");
        }
        //表未应用时不能更换主键
        if(StringUtil.isEmpty(result)){
            result =  checkIsApply(table.getStr("RESOURCETABLE_ISCREATE"));
        }

        boolean columnIsExistsOfCurrentTable = checkNewPrimaryKeyIsExistsOfCurrentTable(table.getStr("RESOURCETABLE_TABLECODE")
                ,newPrimaryKey);
        //如果是视图，并且输入的新主键不属于当前视图的列，不能更换主键
        if(StringUtil.isEmpty(result)&&TableTypeEnum.VIEW.getValue().equals(table.getStr("RESOURCETABLE_TYPE"))){
            if(!columnIsExistsOfCurrentTable){
                result = MessageUtils.getMessage("table.view.column.notExistent");
            }
        }

        //如果当前表没有主键，并且新的主键编码不属于该表字段，则不能替换主键
        DynaBean column = metaService.selectOne("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_TYPE","ID")
                        .eq("TABLECOLUMN_RESOURCETABLE_ID",table.getStr("JE_CORE_RESOURCETABLE_ID")));
        if(column==null&&!columnIsExistsOfCurrentTable){
            result = MessageUtils.getMessage("table.column.notExistent.and.primarykey.notExistent");
        }

        //如果是其他表的外键，不能更换主键
        if(StringUtil.isEmpty(result)){
            result = checkIsForeignKeyOfOtherTables(
                    table.getStr("RESOURCETABLE_PARENTTABLECODES")
                    ,table.getStr("RESOURCETABLE_CHILDTABLECODES"),table.getStr("RESOURCETABLE_PKCODE"));
        }

        return result;
    }

    public String getPkCode(String tableCode) {
        if(StringUtil.isEmpty(tableCode)){
            return null;
        }

        DynaBean dynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_TABLECODE",tableCode).eq("TABLECOLUMN_TYPE","ID"));
        if(dynaBean==null){
            return null;
        }
        return dynaBean.getStr("TABLECOLUMN_CODE");
    }

    @Override
    public String checkIsExistsData(String tableCode, String productCode) {
        long count;
        if(PRODUCT_CORE_META.equals(productCode)){
            count = getDataCount(tableCode);
        }else{
            CommonTableRpcService commonTableRpcService   = RpcSchemaFactory.getRemoteProvierClazz(productCode,
                    "commonTableRpcService", CommonTableRpcService.class);
            count = commonTableRpcService.getDataCount(tableCode);
        }
        if(count>0){
            return MessageUtils.getMessage("table.exist.data");
        }
        return null;
    }

    public long getDataCount(String tableCode) {
        List<Map<String,Object>> list = metaService.selectSql(ConditionsWrapper.builder()
                .apply(StringUtil.isNotEmpty(tableCode),"Select count(1) as count from "+ tableCode ));
        if(list!=null){
            return list.get(0).get("count")==null?0L:Long.parseLong(list.get(0).get("count").toString());
        }
        return 0L;
    }

    public String checkIsApply(String isCreate) {
        if(!"1".equals(isCreate)){
            return MessageUtils.getMessage("table.not.apply");
        }
        return null;
    }

    public String checkIsForeignKeyOfOtherTables(String parentTableCodes, String childTableCodes,String oldPrimaryKey) {
        if (StringUtil.isEmpty(parentTableCodes) || StringUtil.isEmpty(childTableCodes)) {
            String[] parentArr = new String[0];
            String[] childArr = new String[0];
            if (StringUtil.isNotEmpty(parentTableCodes)) {
                parentArr = parentTableCodes.split(ArrayUtils.SPLIT);
            }
            if (StringUtil.isNotEmpty(childTableCodes)) {
                childArr = childTableCodes.split(ArrayUtils.SPLIT);
            }
            for (int i = 0; i < parentArr.length; i++) {
                String parentCode = parentArr[i];
                if (StringUtil.isNotEmpty(parentCode)) {
                    List<DynaBean> parentKeys = metaService.select("JE_CORE_TABLEKEY",
                            ConditionsWrapper.builder().eq("TABLEKEY_LINKTABLE", parentCode).eq("TABLEKEY_CODE", oldPrimaryKey));
                    if (!(null == parentKeys || parentKeys.size() == 0)) {
                        return MessageUtils.getMessage("table.id.key",parentCode);
                    }
                }
            }
            for (int i = 0; i < childArr.length; i++) {
                String childCode = childArr[i];
                if (StringUtil.isNotEmpty(childCode)) {
                    List<DynaBean> childKeys = metaService.select("JE_CORE_TABLEKEY",
                            ConditionsWrapper.builder().eq("TABLEKEY_TABLECODE", childCode).eq("TABLEKEY_LINECOLUMNCODE", oldPrimaryKey));
                    if (!(null == childKeys || childKeys.size() == 0)) {
                        return MessageUtils.getMessage("table.id.key",childCode);
                    }
                }
            }
        }

        return null;

    }

    @Override
    public boolean checkNewPrimaryKeyIsExistsOfCurrentTable(String tableCode, String newPrimaryKey) {
        DynaBean dynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_CODE",newPrimaryKey).eq("TABLECOLUMN_TABLECODE",tableCode));
        if(dynaBean!=null){
            return true;
        }
        return false;
    }

    @Override
    public String checkPrimaryKeyBelongToView(String pkValue, String pkCode) {

        return null;
    }
    @Transactional
    public void replacePrimaryKeyOfResourceTable(DynaBean tableInfo,String oldPrimaryKey,String newPrimaryKey,boolean isColumnOfCurrentTable) {
        String tableType = tableInfo.getStr("RESOURCETABLE_TYPE");
        if("VIEW".equals(tableType)){
            replacePrimaryKeyForView(tableInfo,newPrimaryKey,isColumnOfCurrentTable);
        }else{
            replacePrimaryKeyForPT(tableInfo,oldPrimaryKey,newPrimaryKey,isColumnOfCurrentTable);
        }
        //清缓存
        tableCache.removeCache(tableInfo.getStr("RESOURCETABLE_TABLECODE"));

    }

    @Transactional
    public void replacePrimaryKeyOfEdgeTable(String tableCode, String oldPrimaryKey, String newePrimaryKey,String tableType,boolean columnIsExistsOfCurrentTable) {
        List<DynaBean> funcList = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder()
                        .eq("FUNCINFO_TABLENAME", tableCode));


        for (DynaBean func : funcList) {
            String funcinfoId = func.getStr("JE_CORE_FUNCINFO_ID");

            DynaBean funcColumn = metaService.selectOne("JE_CORE_RESOURCECOLUMN",
                    ConditionsWrapper.builder()
                            .eq("RESOURCECOLUMN_FUNCINFO_ID", funcinfoId)
                            .eq("RESOURCECOLUMN_CODE", oldPrimaryKey));

            if(columnIsExistsOfCurrentTable){
                DynaBean funcNewColumn = metaService.selectOne("JE_CORE_RESOURCECOLUMN",
                        ConditionsWrapper.builder()
                                .eq("RESOURCECOLUMN_FUNCINFO_ID", funcinfoId)
                                .eq("RESOURCECOLUMN_CODE", newePrimaryKey));
                //更换是否是主键的标识

                if(funcNewColumn!=null){
                    if(!"VIEW".equals(tableType)){
                        funcNewColumn.setStr("RESOURCECOLUMN_INDEX","1");
                    }
                    funcNewColumn.setStr("RESOURCECOLUMN_ISPK","1");
                    metaService.update(funcNewColumn);
                }

                if(funcColumn!=null){
                    if(!"VIEW".equals(tableType)){
                        funcColumn.setStr("RESOURCECOLUMN_INDEX","0");
                    }
                    funcColumn.set("RESOURCECOLUMN_ISPK", "0");
                    metaService.update(funcColumn);
                }
            }else{
                //更换主键字段
                if (null != funcColumn) {
                    funcColumn.set("RESOURCECOLUMN_CODE", newePrimaryKey);
                    metaService.update(funcColumn);
                }
            }


            DynaBean funcField = metaService.selectOne("JE_CORE_RESOURCEFIELD",
                    ConditionsWrapper.builder()
                            .eq("RESOURCEFIELD_FUNCINFO_ID", funcinfoId)
                            .eq("RESOURCEFIELD_CODE", oldPrimaryKey));

            //如果是不是新加的字段，则跳过
            if(!columnIsExistsOfCurrentTable){
                if (null != funcField) {
                    funcField.set("RESOURCEFIELD_CODE", newePrimaryKey);
                    metaService.update(funcField);
                }
            }

            //修改功能主键名称
            metaService.executeSql("UPDATE JE_CORE_FUNCINFO SET FUNCINFO_PKNAME='"+newePrimaryKey +"' WHERE JE_CORE_FUNCINFO_ID='"+funcinfoId+"'");
            //清除缓存
            metaStaticizeService.removeCache(func.getStr("FUNCINFO_FUNCCODE"),func.getStr("SY_PRODUCT_CODE"));
        }

    }

    @Override
    public void updateMeta(DynaBean tableInfo, String newPrimaryKey) {
       boolean columnIsExistsOfCurrentTable = checkNewPrimaryKeyIsExistsOfCurrentTable(tableInfo.getStr("RESOURCETABLE_TABLECODE"),newPrimaryKey);

        replacePrimaryKeyOfResourceTable(tableInfo,tableInfo.getStr("RESOURCETABLE_PKCODE"),newPrimaryKey,columnIsExistsOfCurrentTable);

        replacePrimaryKeyOfEdgeTable(tableInfo.getStr("RESOURCETABLE_TABLECODE"),
                tableInfo.getStr("RESOURCETABLE_PKCODE"),newPrimaryKey,tableInfo.getStr("RESOURCETABLE_TYPE"),columnIsExistsOfCurrentTable);
    }

    private void replacePrimaryKeyForView(DynaBean tableInfo, String newPrimaryKey,boolean isColumnOfCurrentTable) {
        //更新表格列
        updatePrimaryKeyForColumn(tableInfo.getStr("JE_CORE_RESOURCETABLE_ID"),newPrimaryKey,isColumnOfCurrentTable);
        updatePrimaryKeyForKey(tableInfo,newPrimaryKey);
        //更新资源表数据
        updatePrimaryKeyForTable(tableInfo.getStr("JE_CORE_RESOURCETABLE_ID"),newPrimaryKey);
    }

    private void replacePrimaryKeyForPT(DynaBean tableInfo, String oldPrimaryKey,String newPrimaryKey,boolean isColumnOfCurrentTable) {
        //更新列
        updatePrimaryKeyForColumn(tableInfo.getStr("JE_CORE_RESOURCETABLE_ID"),newPrimaryKey,isColumnOfCurrentTable);
        //更新键，不用区分新键是否是当前表字段
        updatePrimaryKeyForKey(tableInfo,newPrimaryKey);
        //更新索引
        updatePrimaryKeyForIndex(tableInfo,oldPrimaryKey,newPrimaryKey,isColumnOfCurrentTable);
        //更新资源表
        updatePrimaryKeyForTable(tableInfo.getStr("JE_CORE_RESOURCETABLE_ID"),newPrimaryKey);
    }

    private void updatePrimaryKeyForTable(String tableId, String newPrimaryKey) {
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE",tableId);
        if(dynaBean!=null){
            dynaBean.set("RESOURCETABLE_PKCODE", newPrimaryKey);
            metaService.update(dynaBean,ConditionsWrapper.builder()
                    .eq("JE_CORE_RESOURCETABLE_ID",dynaBean.getStr("JE_CORE_RESOURCETABLE_ID")));
        }
    }

    private void updatePrimaryKeyForIndex(DynaBean table, String oldPrimaryKey, String newPrimaryKey,boolean isColumnOfCurrentTable) {
        String tableId = table.getStr("JE_CORE_RESOURCETABLE_ID");
        DynaBean oldKeyDynaBean = metaService.selectOne("JE_CORE_TABLEINDEX",ConditionsWrapper.builder()
                .eq("TABLEINDEX_RESOURCETABLE_ID", tableId)
                .eq("TABLEINDEX_FIELDCODE", oldPrimaryKey));
        DynaBean newKeyDynaBean =null;
        if(isColumnOfCurrentTable){
             newKeyDynaBean = metaService.selectOne("JE_CORE_TABLEINDEX",ConditionsWrapper.builder()
                    .eq("TABLEINDEX_RESOURCETABLE_ID", tableId)
                    .eq("TABLEINDEX_FIELDCODE", newPrimaryKey));
        }

        DynaBean dynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID",tableId)
                        .eq("TABLECOLUMN_CODE",newPrimaryKey));
        if(oldKeyDynaBean!=null && newKeyDynaBean==null){
            oldKeyDynaBean.set("TABLEINDEX_FIELDNAME", dynaBean.getStr("TABLECOLUMN_NAME"));
            oldKeyDynaBean.set("TABLEINDEX_FIELDCODE", newPrimaryKey);
            metaService.update(oldKeyDynaBean);
        }

        if(oldKeyDynaBean==null){
            DynaBean index = new DynaBean();
            index.table("JE_CORE_TABLEINDEX");
            index.setStr("TABLEINDEX_FIELDCODE",newPrimaryKey);
            index.setStr("TABLEINDEX_FIELDNAME",dynaBean.getStr("TABLECOLUMN_NAME"));
            index.setStr("TABLEINDEX_TABLECODE",table.getStr("RESOURCETABLE_TABLECODE"));
            index.setStr("TABLEINDEX_NAME","JE_"+JEUUID.uuid());
            index.setStr("TABLEINDEX_RESOURCETABLE_ID",tableId);
            index.setStr("TABLEINDEX_UNIQUE","1");
            index.setStr("TABLEINDEX_ISCREATE","1");
            index.setStr("TABLEINDEX_CLASSIFY","PRO");
            commonService.buildModelCreateInfo(index);
            metaService.insert(index);
        }
    }

    private void updatePrimaryKeyForKey(DynaBean table, String newPrimaryKey) {
        DynaBean dynaBean = metaService.selectOne("JE_CORE_TABLEKEY",
                ConditionsWrapper.builder().eq("TABLEKEY_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"))
                        .eq("TABLEKEY_TYPE", "Primary"));

        if(dynaBean!=null){
            dynaBean.set("TABLEKEY_COLUMNCODE", newPrimaryKey);
            metaService.update(dynaBean);
        }
        //导入的表若没有主键，在更换主键时会赋予该表一个主键，所以同时在表格键中增加一个主键
        if(dynaBean==null){
            DynaBean key = new DynaBean();
            key.table("JE_CORE_TABLEKEY");
            key.setStr("TABLEKEY_COLUMNCODE",newPrimaryKey);
            key.setStr("TABLEKEY_CODE","JE_"+ JEUUID.uuid());
            key.setStr("TABLEKEY_TYPE","Primary");
            key.setStr("TABLEKEY_RESOURCETABLE_ID",table.getStr("JE_CORE_RESOURCETABLE_ID"));
            key.setStr("TABLEKEY_ISRESTRAINT","1");
            key.setStr("TABLEKEY_ISCREATE","1");
            key.setStr("TABLEKEY_TABLECODE",table.getStr("RESOURCETABLE_TABLECODE"));
            commonService.buildModelCreateInfo(key);
            metaService.insert(key);
        }

    }

    private void updatePrimaryKeyForColumn(String tableId, String newPrimaryKey,boolean isColumnOfCurrentTable) {
        DynaBean oldKeyDynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID",tableId)
                                            .eq("TABLECOLUMN_TYPE","ID"));

        DynaBean table = metaService.selectOneByPk("JE_CORE_RESOURCETABLE",tableId);
        String tableType =table.getStr("RESOURCETABLE_TYPE");
        if("VIEW".equals(tableType)){
            updateViewPrimaryKeyForColumn(oldKeyDynaBean,tableId,newPrimaryKey,isColumnOfCurrentTable);
        }else{
            updatePtTablePrimaryKeyForColumn(table,oldKeyDynaBean,newPrimaryKey,isColumnOfCurrentTable);
        }

    }

    private void updatePtTablePrimaryKeyForColumn(DynaBean table,DynaBean oldKeyDynaBean,String newPrimaryKey, boolean isColumnOfCurrentTable) {
        if(isColumnOfCurrentTable){
            //从实体表中获取列的类型
            DynaBean tableInfoOnDb = getTableInfoFromDb(table);
            if(oldKeyDynaBean!=null){
                oldKeyDynaBean.setStr("TABLECOLUMN_TYPE",getPrimaryKeyColumnType(tableInfoOnDb,oldKeyDynaBean.getStr("TABLECOLUMN_CODE")));
                metaService.update(oldKeyDynaBean);
            }

            DynaBean newKeyDynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                    ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID",table.getStr("JE_CORE_RESOURCETABLE_ID"))
                            .eq("TABLECOLUMN_CODE",newPrimaryKey));
            //若新的主键是当前表的字段，要替换字段类型
            if(newKeyDynaBean!=null){
                newKeyDynaBean.setStr("TABLECOLUMN_TYPE","ID");
                metaService.update(newKeyDynaBean);
            }

        }else{
            //若新的主键不是当前表的字段，直接替换即可
            if(oldKeyDynaBean!=null){
                oldKeyDynaBean.setStr("TABLECOLUMN_CODE",newPrimaryKey);
                oldKeyDynaBean.set("TABLECOLUMN_OLDCODE", newPrimaryKey);

                metaService.update(oldKeyDynaBean);
            }
        }

    }

    public DynaBean getTableInfoFromDb(DynaBean table){
        //从实体表中获取列的类型
        DynaBean tableInfoOnDb = null;
        if(PRODUCT_CORE_META.equals(table.getStr("SY_PRODUCT_CODE"))){
            tableInfoOnDb= DataBaseUtils.buildDynabeanTableInfo(table);
        }else{
            CommonTableRpcService commonTableRpcService   = RpcSchemaFactory.getRemoteProvierClazz(table.getStr("SY_PRODUCT_CODE"),
                    "commonTableRpcService", CommonTableRpcService.class);
            tableInfoOnDb= commonTableRpcService.getResourcetableInfoByDB(table);
        }

        return tableInfoOnDb;
    }

    /**
     *
     * @param oldKeyDynaBean
     * @param tableId
     * @param newPrimaryKey
     * @param isColumnOfCurrentTable
     */
    private void updateViewPrimaryKeyForColumn(DynaBean oldKeyDynaBean,String tableId, String newPrimaryKey,boolean isColumnOfCurrentTable) {
        /**
         * 问题：
         * 1.若是导入进来的视图，是没有主键的
         */
        if (isColumnOfCurrentTable) {
            //修改旧主键列和新主键列的字段类型和视图配置
            //更新旧键
            if(oldKeyDynaBean!=null){

                DynaBean baseTableInfo = metaService.selectOneByPk("JE_CORE_RESOURCETABLE",tableId);
                DynaBean tableInfoOnDb = getTableInfoFromDb(baseTableInfo);
                String olumnType = getPrimaryKeyColumnType(tableInfoOnDb,oldKeyDynaBean.getStr("TABLECOLUMN_CODE"));

                String viewConfig = oldKeyDynaBean.getStr("TABLECOLUMN_VIEWCONFIG");
                JSONObject jsonObject = StringUtil.isNotEmpty(viewConfig)? JSON.parseObject(viewConfig):null;
                if(jsonObject!=null){
                    jsonObject.put("dataType",olumnType);
                    oldKeyDynaBean.setStr("TABLECOLUMN_VIEWCONFIG",jsonObject.toJSONString());
                }
                oldKeyDynaBean.setStr("TABLECOLUMN_TYPE",olumnType);
                metaService.update(oldKeyDynaBean);
            }
            //更新新键
            DynaBean newKeyDynaBean = metaService.selectOne("JE_CORE_TABLECOLUMN",
                    ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID",tableId)
                            .eq("TABLECOLUMN_CODE",newPrimaryKey));
            String viewConfig = newKeyDynaBean.getStr("TABLECOLUMN_VIEWCONFIG");
            JSONObject jsonObject = StringUtil.isNotEmpty(viewConfig)? JSON.parseObject(viewConfig):null;
            if(jsonObject!=null){
                jsonObject.put("dataType","ID");
                newKeyDynaBean.setStr("TABLECOLUMN_VIEWCONFIG",jsonObject.toJSONString());
            }
            newKeyDynaBean.setStr("TABLECOLUMN_TYPE","ID");
            metaService.update(newKeyDynaBean);
        }
    }

    private String getPrimaryKeyColumnType(DynaBean table, String oldPkCode) {
        List<Object> list = (List<Object>) table.get("$TABLECOLUMNS$");
        for(Object object:list){
            HashMap values = new HashMap();
            if(object instanceof Map){
                Map<String,Object> map = (Map<String, Object>) object;
                values = (HashMap) map.get("values");
            }
            if(object instanceof DynaBean){
                DynaBean dynaBean = (DynaBean) object;
                values = dynaBean.getValues();
            }
            String code = values.get("TABLECOLUMN_CODE")==null?"":values.get("TABLECOLUMN_CODE").toString();
            if(oldPkCode.equals(code)){
                String columnType = values.get("TABLECOLUMN_TYPE")==null?"":values.get("TABLECOLUMN_TYPE").toString();
                if(!"ID".equals(columnType)&&StringUtil.isNotEmpty(columnType)){
                    return columnType;
                }
                return values.get("TABLECOLUMN_PRIMARY_KEY_TYPE")==null?"VARCHAR50":values.get("TABLECOLUMN_PRIMARY_KEY_TYPE").toString();
            }
        }

        return "VARCHAR50";
    }
}
